package ram;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Manager {

    public static void main(String[] args) throws IOException {
        new Manager(PORTA);
    }

    public static final int PORTA = 55442;

    private final ServerSocket server;

    private boolean close;

    private final ArrayList<Exception> logErros = new ArrayList<Exception>();

    private final ArrayList<Mensagem> mensagens = new ArrayList<Mensagem>();

    private final Thread receiveThread;

    public Manager(int port) throws IOException {
        server = new ServerSocket(port);
        close = false;

        receiveThread = new Thread() {

            private ManagerReceive receive = null;

            @Override
            public void run() {
                while (!close) {
                    try {

                        Socket socket = server.accept();

                        receive = new ManagerReceive(socket, mensagens, logErros);
                        receive.start();

                    } catch (IOException e) {
                        logErros.add(e);
                    }
                }
                this.receive.stop();
            }
        };
        receiveThread.start();

    }

    public ArrayList<Mensagem> getMensagens() {
        return mensagens;
    }

    public ArrayList<Exception> getLogErros() {
        return logErros;
    }

    public void clearLogErros() {
        logErros.clear();
    }

    public void stop() {
        this.close = true;
        this.receiveThread.stop();
    }
}
